import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 如果已经明确设置了 Authorization header，则不覆盖
    if (!config.headers.Authorization) {
      // 优先使用 doctorToken，如果为空或不存在则使用 adminToken
      let token = localStorage.getItem('doctorToken')
      if (!token || token.trim() === '') {
        token = localStorage.getItem('adminToken')
      }
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('doctorToken')
      localStorage.removeItem('adminToken')
      localStorage.removeItem('level')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

/**
 * 通用图片上传接口
 * @param {FormData} formData - 包含文件和类型的FormData
 * @param {string} type - 文件类型 (avatar, cover, push_cover)
 * @returns {Promise} 上传结果
 */
export const uploadImage = (formData, type = 'avatar') => {
  // 确保FormData包含type参数
  if (!formData.has('type')) {
    formData.append('type', type)
  }
  
  return api.post('/upload/image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传头像
 * @param {File} file - 头像文件
 * @returns {Promise} 上传结果
 */
export const uploadAvatar = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'avatar')
  
  return uploadImage(formData, 'avatar')
}

/**
 * 上传活动封面
 * @param {File} file - 封面文件
 * @returns {Promise} 上传结果
 */
export const uploadCover = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'cover')
  
  return uploadImage(formData, 'cover')
}

/**
 * 上传推送封面
 * @param {File} file - 封面文件
 * @returns {Promise} 上传结果
 */
export const uploadPushCover = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'push_cover')
  
  return uploadImage(formData, 'push_cover')
}
